package com.lawyer.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.lawyer.entity.Config;
import com.lawyer.entity.MoneyFlows;
import com.lawyer.entity.RegimentalMember;
import com.lawyer.entity.RiderOrder;
import com.lawyer.entity.User;
import com.lawyer.entity.view.OrderRecommendView;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.lawyer.repository.ConfigRepository;
import com.lawyer.repository.MoneyFlowsRepository;
import com.lawyer.repository.RegimentalMemberRepository;
import com.lawyer.repository.RiderOrderRepository;
import com.lawyer.repository.UserRepository;

@RestController
@RequestMapping(value = "/riderOrder")
@Api(tags = "赔付订单管理")
@SuppressWarnings("all")
public class RiderOrderController {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private MoneyFlowsRepository moneyFlowsRepository;

	@Autowired
	private RiderOrderRepository riderOrderRepository;
	@Autowired
	private RegimentalMemberRepository regimentalMemberRepository;

	@Autowired
	private EntityManager entityManager;

	@Autowired
	private ConfigRepository configRepository;

	@ApiOperation(httpMethod = "POST", value = "提交订单", notes = "提交订单")
	@RequestMapping(value = "/saveOrder", method = RequestMethod.POST)
	public HttpEntity<?> saveOrder(@RequestBody RiderOrder order) {
		Message msg = new Message();
		try {
			User user = userRepository.findOne(order.getUserId());
			if (user != null) {
				order.setHeaderIco(user.getHeaderIco());
				order.setOrderStatus("未签约");
				order.setCommission(0D);
				order.setOrderAmount(0D);
				RegimentalMember regiment = regimentalMemberRepository.findByMemberId(order.getUserId());
				if (regiment != null) {
					order.setLeaderId(regiment.getLeaderId());
					order.setLeaderHeaderIco(regiment.getLeaderHeaderIco());
					order.setLeaderName(regiment.getLeaderName());
				}
				riderOrderRepository.save(order);
			} else {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("用户不存在");
			}

		} catch (Exception e) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "DELETE", value = "删除订单", notes = "删除订单")
	@RequestMapping(value = "/deleteOrder", method = RequestMethod.DELETE)
	public HttpEntity<?> deleteOrder(Integer orderId) {
		Message msg = new Message();
		try {
			RiderOrder order = riderOrderRepository.findOne(orderId);
			if (order != null) {
				riderOrderRepository.delete(orderId);
			} else {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("订单不存在");
			}

		} catch (Exception e) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "GET", value = "我的赔付订单", notes = "我的赔付订单")
	@RequestMapping(value = "/myRiderOrder", method = RequestMethod.GET)
	@ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query", value = "第几页"),
			@ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", value = "分页条数") })
	public HttpEntity<?> myRiderOrder(String orderStatus, String userId, @PageableDefault(page = 0, sort = { "createdDate" }, direction = Sort.Direction.DESC) Pageable pageable) {
		Message msg = new Message();

		if (StringUtils.isEmpty(userId)) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage("userId为空或用户不存在");
			return new ResponseEntity<>(msg, HttpStatus.OK);
		}

		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

		CriteriaQuery<RiderOrder> criteriaQuery = criteriaBuilder.createQuery(RiderOrder.class);

		Root<RiderOrder> root = criteriaQuery.from(RiderOrder.class);

		criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createdDate")));

		// 查询条件
		List<Predicate> predicates = new ArrayList<>();

		if (StringUtils.isNotEmpty(orderStatus) && !"全部".equals(orderStatus)) {
			predicates.add(criteriaBuilder.equal(root.get("orderStatus"), orderStatus));
		}

		// 查询条件or 或者
		Predicate pred1 = criteriaBuilder.equal(root.get("userId"), userId);
		Predicate pred2 = criteriaBuilder.equal(root.get("leaderId"), userId);
		predicates.add(criteriaBuilder.or(pred1, pred2));

		// 将所有条件用 and 联合起来
		if (!CollectionUtils.isEmpty(predicates)) {
			criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
		}

		List<RiderOrder> counts = entityManager.createQuery(criteriaQuery).getResultList();
		TypedQuery<RiderOrder> createQuery = entityManager.createQuery(criteriaQuery);
		createQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
		createQuery.setMaxResults(pageable.getPageSize());

		Page page = new PageImpl<RiderOrder>(createQuery.getResultList(), pageable, counts.size());

		msg.setData(page);

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "GET", value = "订单详情", notes = "订单详情")
	@RequestMapping(value = "/riderOrderInfo", method = RequestMethod.GET)
	public HttpEntity<?> riderOrderInfo(Integer orderId) {
		Message msg = new Message();

		RiderOrder order = riderOrderRepository.findOne(orderId);
		RegimentalMember regiment = regimentalMemberRepository.findByMemberId(order.getUserId());
		
		if (regiment != null) {
			User userInfo = userRepository.findOne(order.getUserId());
			order.setLeaderId(regiment.getLeaderId());
			order.setLeaderHeaderIco(regiment.getLeaderHeaderIco());
			order.setLeaderName(regiment.getLeaderName());
		}
		msg.setData(order);
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

}
